document.addEventListener('DOMContentLoaded', () => {
  const loveForm = document.getElementById('loveForm');
  const anniversaryForm = document.getElementById('anniversaryForm');
  const daysCountElement = document.getElementById('daysCount');
  const loveDaysElement = document.getElementById('loveDays');
  const anniversaryList = document.getElementById('anniversaryList');
  const settingsButton = document.getElementById('settingsButton');
  const anniversaryButton = document.getElementById('anniversaryButton');
  const addAnniversaryButton = document.getElementById('addAnniversaryButton');
  const settingsModal = document.getElementById('settingsModal');
  const anniversaryModal = document.getElementById('anniversaryModal');
  const birthdayModal = document.getElementById('birthdayModal');
  const closeModal = document.querySelectorAll('.close');
  const startDateInput = document.getElementById('startDate');
  const maleAvatar = document.getElementById('maleAvatar');
  const femaleAvatar = document.getElementById('femaleAvatar');
  const maleAvatarInput = document.getElementById('maleAvatarInput');
  const femaleAvatarInput = document.getElementById('femaleAvatarInput');
  const maleBirthday = document.getElementById('maleBirthday');
  const femaleBirthday = document.getElementById('femaleBirthday');
  const birthdayForm = document.getElementById('birthdayForm');
  const calendarType = document.getElementById('calendarType');
  const solarBirthdayContainer = document.getElementById('solarBirthdayContainer');
  const lunarBirthdayContainer = document.getElementById('lunarBirthdayContainer');
  const changeBackgroundButton = document.getElementById('changeBackgroundButton');
  const backgroundInput = document.getElementById('backgroundInput');
  let currentBirthdayElement = null;

  function calculateLoveDays(startDate) {
    const currentDate = new Date();
    const timeDifference = currentDate - new Date(startDate);
    return Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  }

  function openSettingsModal() {
    const savedStartDate = localStorage.getItem('startDate');
    if (savedStartDate) {
      startDateInput.value = savedStartDate;
    }
    settingsModal.style.display = 'block';
  }

  settingsButton.addEventListener('click', openSettingsModal);
  loveDaysElement.addEventListener('click', openSettingsModal);

  function openAnniversaryModal() {
    anniversaryModal.style.display = 'block';
  }

  anniversaryButton.addEventListener('click', openAnniversaryModal);
  addAnniversaryButton.addEventListener('click', openAnniversaryModal);

  closeModal.forEach(button => {
    button.addEventListener('click', () => {
      settingsModal.style.display = 'none';
      anniversaryModal.style.display = 'none';
      birthdayModal.style.display = 'none';
    });
  });

  window.addEventListener('click', (event) => {
    if (event.target === settingsModal) {
      settingsModal.style.display = 'none';
    }
    if (event.target === anniversaryModal) {
      anniversaryModal.style.display = 'none';
    }
    if (event.target === birthdayModal) {
      birthdayModal.style.display = 'none';
    }
  });

  loveForm.addEventListener('submit', (event) => {
    event.preventDefault();
    const startDate = startDateInput.value;
    const currentDate = new Date().toISOString().split('T')[0];

    if (startDate > currentDate) {
      alert('相爱日期不能大于今天');
      return;
    }

    localStorage.setItem('startDate', startDate);
    daysCountElement.textContent = calculateLoveDays(startDate);
    settingsModal.style.display = 'none';
  });


  anniversaryForm.addEventListener('submit', (event) => {
    event.preventDefault();
    const anniversaryDate = document.getElementById('anniversaryDate').value;
    const anniversaryName = document.getElementById('anniversaryName').value;
    const anniversaries = JSON.parse(localStorage.getItem('anniversaries')) || [];
    anniversaries.push({ date: anniversaryDate, name: anniversaryName });
    localStorage.setItem('anniversaries', JSON.stringify(anniversaries));
    displayAnniversaries();
    anniversaryModal.style.display = 'none';
  });

  function displayAnniversaries() {
    const anniversaries = JSON.parse(localStorage.getItem('anniversaries')) || [];
    anniversaryList.innerHTML = '';
    anniversaries.forEach((anniversary, index) => {
      const listItem = document.createElement('li');
      listItem.textContent = `${anniversary.name} - ${anniversary.date}`;
      listItem.addEventListener('click', () => {
        anniversaries.splice(index, 1);
        localStorage.setItem('anniversaries', JSON.stringify(anniversaries));
        displayAnniversaries();
      });
      anniversaryList.appendChild(listItem);
    });
  }

  const savedStartDate = localStorage.getItem('startDate');
  if (savedStartDate) {
    daysCountElement.textContent = calculateLoveDays(savedStartDate);
  } else {
    daysCountElement.textContent = 520; // 默认显示520天
  }

  displayAnniversaries();

  maleAvatar.addEventListener('click', () => {
    maleAvatarInput.click();
  });

  femaleAvatar.addEventListener('click', () => {
    femaleAvatarInput.click();
  });

  maleAvatarInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        maleAvatar.src = e.target.result;
        localStorage.setItem('maleAvatar', e.target.result);
      };
      reader.readAsDataURL(file);
    }
  });

  femaleAvatarInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        femaleAvatar.src = e.target.result;
        localStorage.setItem('femaleAvatar', e.target.result);
      };
      reader.readAsDataURL(file);
    }
  });

  // 生日修改功能
  maleBirthday.addEventListener('click', () => {
    currentBirthdayElement = maleBirthday;
    birthdayModal.style.display = 'block';
  });

  femaleBirthday.addEventListener('click', () => {
    currentBirthdayElement = femaleBirthday;
    birthdayModal.style.display = 'block';
  });

  calendarType.addEventListener('change', () => {
    if (calendarType.value === 'solar') {
      solarBirthdayContainer.style.display = 'block';
      lunarBirthdayContainer.style.display = 'none';
    } else {
      solarBirthdayContainer.style.display = 'none';
      lunarBirthdayContainer.style.display = 'block';
    }
  });

  birthdayForm.addEventListener('submit', (event) => {
    event.preventDefault();
    const calendarTypeValue = calendarType.value;
    let birthdayValue;
    if (calendarTypeValue === 'solar') {
      birthdayValue = document.getElementById('solarBirthday').value;
      if (birthdayValue) {
        const date = new Date(birthdayValue);
        const month = date.getMonth() + 1;
        const day = date.getDate();
        currentBirthdayElement.textContent = `${month}月${day}日`;
        currentBirthdayElement.dataset.birthday = birthdayValue;
        localStorage.setItem(currentBirthdayElement.id, birthdayValue);
      }
    } else {
      birthdayValue = document.getElementById('lunarBirthday').value;
      if (birthdayValue) {
        alert('农历转换功能尚未实现');
      }
    }
    birthdayModal.style.display = 'none';
  });

  // 更换背景功能
  changeBackgroundButton.addEventListener('click', () => {
    backgroundInput.click();
  });

  backgroundInput.addEventListener('change', (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        document.body.style.backgroundImage = `url(${e.target.result})`;
        localStorage.setItem('backgroundImage', `url(${e.target.result})`);
      };
      reader.readAsDataURL(file);
    }
  });

  // 加载本地存储的头像和生日
  const savedMaleAvatar = localStorage.getItem('maleAvatar');
  if (savedMaleAvatar) {
    maleAvatar.src = savedMaleAvatar;
  }

  const savedFemaleAvatar = localStorage.getItem('femaleAvatar');
  if (savedFemaleAvatar) {
    femaleAvatar.src = savedFemaleAvatar;
  }

  const savedMaleBirthday = localStorage.getItem('maleBirthday');
  if (savedMaleBirthday) {
    const date = new Date(savedMaleBirthday);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    maleBirthday.textContent = `${month}月${day}日`;
    maleBirthday.dataset.birthday = savedMaleBirthday;
  }

  const savedFemaleBirthday = localStorage.getItem('femaleBirthday');
  if (savedFemaleBirthday) {
    const date = new Date(savedFemaleBirthday);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    femaleBirthday.textContent = `${month}月${day}日`;
    femaleBirthday.dataset.birthday = savedFemaleBirthday;
  }

  // 加载本地存储的背景
  const savedBackgroundImage = localStorage.getItem('backgroundImage');
  if (savedBackgroundImage) {
    document.body.style.backgroundImage = savedBackgroundImage;
  }
});